<?php
namespace WDB\Wrapper;
use WDB,
    WDB\Exception;

/**
 * Base class for common column wrapper implementation.
 *
 * @author Richard Ejem <richard(at)ejem.cz>
 * @package WDB
 */
abstract class AbstractColumn extends WDB\BaseObject implements iColumn, iOrderable, iFilterable
{
    /**@var WDB\Validation\ColumnRules */
    protected $rules;

    /**@var iTable */
    protected $table;

    /**@var WDB\Event\Event*/
    protected $onSaved;

    /**@var int bitmask of display modes to add to column webui*/
    public $addDisplayModes = 0;

    /**@var int bitmask of display modes to remove from column webui*/
    public $removeDisplayModes = 0;

    protected function __construct(iTable $tableWrapper)
    {
        $this->table = $tableWrapper;
        $this->rules = new WDB\Validation\ColumnRules($this->title);
        $this->onSaved = new WDB\Event\Event();
    }

    // <editor-fold defaultstate="collapsed" desc="iColumn implementation">
    public function getDefault()
    {
        return NULL;
    }

    public function getTable()
    {
        return $this->table;
    }


    public  function getTitle()
    {
        return $this->getName();
    }

    public function getRules()
    {
        return $this->rules;
    }

    public function isNullable()
    {
        return TRUE;
    }

    public function rule($rule, $message = NULL, $argument = NULL)
    {
        $this->rules->set($rule, $message, $argument);
        return $this;
    }

    public function getWebUIClass()
    {
        return NULL;
    }
    public function getWebUIDisplayMode($original = NULL)
    {
        return ($original | $this->addDisplayModes) & ~$this->removeDisplayModes;
    }
    public function isAutoColumn()
    {
        return FALSE;
    }
    public function isAutoIncrement()
    {
        return FALSE;
    }
    public function valueToDatatype($value)
    {
        return WDB\Query\Element\Datatype\AbstractType::createDatatype($value);
    }

    public function valuesEqual($first, $second)
    {
        return $first == $second;
    }

    public function createField($isNew, $value, WDB\Query\SelectedRow $row = NULL)
    {
        return new Field($this, $isNew, $this->setFieldValue($value));
    }

    public function saveToRow(array &$row, $value)
    {
        $row[$this->name] = $value;
    }

    public function getOnSaved()
    {
        return $this->onSaved;
    }

    public function raiseOnSaved(WDB\Wrapper\iRecord $record)
    {
        $this->onSaved->raise($record);
    }

    public function isOrderable()
    {
        return false;
    }

    public function getFieldValue($value)
    {
        return $value;
    }

    public function setFieldValue($value)
    {
        return $value;
    }

    public function getStringValue($value)
    {
        return $value === NULL ? "=NULL" : preg_replace('~^=NULL~', '==NULL', (string)$value);
    }
    // </editor-fold>
}